package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;
    /**
     * 用户微信登录
      * @param dto
     * @return
     */
    @Override
    public User login(UserLoginDTO dto) {
        //1.通过httpClient，构造登录凭证校验请求
        //1.1构造请求参数
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("appid", weChatProperties.getAppid());
        paramMap.put("secret", weChatProperties.getSecret());
        paramMap.put("js_code", dto.getCode());
        paramMap.put("grant_type", "authorization_code");
        //1.2调用httpClient工具类发送请求,返回的为json格式
        String res = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", paramMap);
        log.info("微信登录返回结果：{}",res);
        //2.解析响应结果获取openId
        //转化为JSONObject对象
        JSONObject jsonObject = JSON.parseObject(res);
        //拿到openid
        String openId =(String) jsonObject.get("openid");
        if(openId == null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //3.判断是否为新用户，根据openId查询数据库user表
        User user = userMapper.selectByOpenId(openId);
        //4.如果是新用户，则新增用户数据
        if(user == null){
            user = new User();
            user.setOpenid(openId);
            user.setCreateTime(LocalDateTime.now());
            user.setName(openId.substring(0,5));
            userMapper.insert(user);
        }
        //如果不是新用户，直接返回user
        return user;
    }
}
